package cn.iocoder.yudao.module.system.service.areaserve;



import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.UserRoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.permission.UserRoleMapper;
import cn.iocoder.yudao.module.system.dal.mysql.user.AdminUserMapper;
import cn.iocoder.yudao.module.system.service.WeChatWorkInterface.TextMsgSendService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.system.controller.admin.areaserve.vo.*;
import cn.iocoder.yudao.module.system.dal.dataobject.areaserve.*;
import cn.iocoder.yudao.module.system.dal.mysql.areaserve.*;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Service
@Validated
@Slf4j
public class AreaReserveServiceImpl implements AreaReserveService {
    @Resource
    private AreaDepartementMapper areaDepartementMapper;

    @Resource
    private AreaResourcesMapper areaResourcesMapper;

    @Resource
    private AreaWorkdayMapper areaWorkdayMapper;

    @Resource
    private AreaBookingQuotaMapper areaBookingQuotaMapper;

    @Resource
    private BookingSeatRecordMapper bookingSeatRecordMapper;

    @Resource
    private MdmEmployeeMapper mdmEmployeeMapper;

    @Resource
    private IsHolidayMapper isHolidayMapper;

    @Resource
    private IsAdjustedWorkdayMapper isAdjustedWorkdayMapper;

    @Resource
    private BookingUserRecordMapper bookingUserRecordMapper;

    @Resource
    private AdminUserService userService;
    @Resource
    private TextMsgSendService textMsgSendService;

    @Resource
    private AdminUserMapper userMapper;

    @Override
    public PageResult<AreaResourcesDO> getAreaResourcesList(AreaResourcesPageReqVO pageReqVO) {
        PageResult<AreaResourcesDO> test = areaResourcesMapper.selectPage(pageReqVO);
        return test;
    }

    public PageResult<AreaDepartementDO> getAreaDepartementList(AreaDepartementPageReqVO pageReqVO) {
        PageResult<AreaDepartementDO> test = areaDepartementMapper.selectPage(pageReqVO);
        return test;
    }

    public PageResult<AreaWorkdayDO> getAreaWorkdayList(AreaWorkdayPageReqVO pageReqVO) {
        PageResult<AreaWorkdayDO> test = areaWorkdayMapper.selectPage(pageReqVO);
        return test;
    }

    public PageResult<AreaBookingQuotaDO> getAreaBookingQuotaList(AreaBookingQuotaPageReqVO pageReqVO) {
        PageResult<AreaBookingQuotaDO> test = areaBookingQuotaMapper.selectPage(pageReqVO);
        return test;
    }

    public PageResult<BookingSeatRecordDO> getBookingSeatRecordList(BookingSeatRecordPageReqVO pageReqVO) {
        PageResult<BookingSeatRecordDO> test = bookingSeatRecordMapper.selectPage(pageReqVO);
        return test;
    }

    public PageResult<MdmEmployeeDO> getMdmEmployeeList(MdmEmployeePageReqVO pageReqVO) {
        PageResult<MdmEmployeeDO> test = mdmEmployeeMapper.selectPage(pageReqVO);
        return test;
    }

    public PageResult<IsHolidayDO> getIsHolidayList(IsHolidayPageReqVO pageReqVO) {
        PageResult<IsHolidayDO> test = isHolidayMapper.selectPage(pageReqVO);
        return test;
    }

    public PageResult<IsAdjustedWorkdayDO> getIsAdjustedWorkdayList(IsAdjustedWorkdayPageReqVO pageReqVO) {
        PageResult<IsAdjustedWorkdayDO> test = isAdjustedWorkdayMapper.selectPage(pageReqVO);
        return test;
    }

    @Autowired
    private RestTemplate restTemplate = new RestTemplate();

    public void syncEmployeeData() {
        String apiUrl = "http://10.233.56.36:8096/d2a/restful/v_employee_api/list";
        UriComponentsBuilder urlBuilder = UriComponentsBuilder.fromHttpUrl(apiUrl)
                .queryParam("EMP_STATUS", "1")
                .queryParam("pageNo", "1")
                .queryParam("pageSize", "10000");
        try {
            // 调用API
            ResponseEntity<String> response = restTemplate.getForEntity(urlBuilder.toUriString(), String.class);

            if (response.getStatusCode().is2xxSuccessful()) {
                String responseBody = response.getBody();
                ObjectMapper objectMapper = new ObjectMapper();
                ApiResponse apiResponse = objectMapper.readValue(responseBody, ApiResponse.class);
                System.out.println("API响应解析成功！");
                System.out.println("Code: " + apiResponse.getCode());
                System.out.println("Msg: " + apiResponse.getMsg());
                System.out.println("Timestamp: " + apiResponse.getStamp());
                List<EmployeeData> employeeDataList = apiResponse.getData();
                if (employeeDataList != null && !employeeDataList.isEmpty()) {
                    for (EmployeeData employeeData : employeeDataList) {
                        MdmEmployeeDO mdmEmployee = new MdmEmployeeDO();
                        mdmEmployee.setWorkdayId(employeeData.workdayId);
                        mdmEmployee.setEmail(employeeData.email);
                        mdmEmployee.setDeptName(employeeData.deptName);
                        mdmEmployee.setDeptCode(employeeData.deptCode);
                        mdmEmployee.setDeptNameOt(employeeData.deptNameOt);
                        mdmEmployee.setEmpStatus(employeeData.empStatus);
                        mdmEmployee.setContractBeginDate(employeeData.contractBeginDate);
                        mdmEmployee.setEmployeeName(employeeData.employeeName);
                        mdmEmployee.setEmployeeCode(employeeData.employeeCode);
                        mdmEmployee.setCompanyName(employeeData.companyName);
                        mdmEmployee.setCompanyNameOt(employeeData.companyNameOt);
                        mdmEmployee.setCompanyCode(employeeData.companyCode);
                        mdmEmployee.setEmployeeNameOt(employeeData.employeeNameOt);
                        mdmEmployee.setDimissionDate(employeeData.dimissionDate);

                        List<MdmEmployeeDO> exist_mdm = mdmEmployeeMapper.selectList(new LambdaQueryWrapperX<MdmEmployeeDO>()
                                .eq(MdmEmployeeDO::getEmployeeCode,mdmEmployee.getEmployeeCode())
                                .eq(MdmEmployeeDO::getEmail,mdmEmployee.getEmail()));

                        if(exist_mdm!= null && !exist_mdm.isEmpty()) {
                            exist_mdm.stream().forEach(e -> {
                                e.setWorkdayId(mdmEmployee.getWorkdayId());
                                e.setDeptName(mdmEmployee.getDeptName());
                                e.setDeptCode(mdmEmployee.getDeptCode());
                                e.setDeptNameOt(mdmEmployee.getDeptNameOt());
                                e.setEmpStatus(mdmEmployee.getEmpStatus());
                                e.setContractBeginDate(mdmEmployee.getContractBeginDate());
                                e.setEmployeeName(mdmEmployee.getEmployeeName());
                                e.setEmployeeCode(mdmEmployee.getEmployeeCode());
                                e.setCompanyName(mdmEmployee.getCompanyName());
                                e.setCompanyNameOt(mdmEmployee.getCompanyNameOt());
                                e.setCompanyCode(mdmEmployee.getCompanyCode());
                                e.setEmployeeNameOt(mdmEmployee.getEmployeeNameOt());
                                e.setDimissionDate(mdmEmployee.getDimissionDate());
                            });
                            mdmEmployeeMapper.updateBatch(exist_mdm);
                        }
                        else {
                            mdmEmployeeMapper.insert(mdmEmployee);
                        }


                        AdminUserDO user = new AdminUserDO();
                        user.setUsername(mdmEmployee.getEmployeeNameOt());
                        user.setNickname(mdmEmployee.getEmployeeName());
                        user.setRemark(mdmEmployee.getEmployeeCode());
                        user.setEmail(mdmEmployee.getEmail());
                        user.setTenantId(1L);
                        user.setDeptId(103L);

                        List<AdminUserDO> exit_user = userMapper.selectList(new LambdaQueryWrapperX<AdminUserDO>()
                                .eq(AdminUserDO::getNickname,user.getNickname())
                                .eq(AdminUserDO::getEmail,user.getEmail())
                                .eq(AdminUserDO::getTenantId,user.getTenantId()));
                        if (exit_user != null && !exit_user.isEmpty()) {
                            exit_user.stream().forEach(e -> {
                                e.setUsername(user.getUsername());
                                e.setRemark(user.getRemark());
                                e.setDeptId(user.getDeptId());

                            });
                            userMapper.updateBatch(exit_user);

                        }
                        else{
                            userMapper.insertOrUpdate(user);
                        }

                    }
                }
            }

        } catch (Exception e) {
            //log.error("调用API时发生异常", e);
            throw new RuntimeException("调用API时发生异常", e);
        }
    }

    public void RefreshAreaBookingQuota(AreaBookingQuotaPageReqVO pageReqVO){
        //删除指定时段内已有的 AreaBookingQuotaDO 数据
        areaBookingQuotaMapper.delete(new LambdaQueryWrapperX<AreaBookingQuotaDO>()
                .betweenIfPresent(AreaBookingQuotaDO::getResourceDate, pageReqVO.getStartResourceDate(), pageReqVO.getEndResourceDate()));

        //获取这一时段诶的 IsHolidayDO 和 IsAdjustedWorkdayDO

        List<IsHolidayDO> listHoliday = isHolidayMapper.selectList(new LambdaQueryWrapperX<IsHolidayDO>().betweenIfPresent(IsHolidayDO::getHolidayDate, pageReqVO.getStartResourceDate(), pageReqVO.getEndResourceDate()));
        List<IsAdjustedWorkdayDO> listAdjustedWorkday = isAdjustedWorkdayMapper.selectList(new LambdaQueryWrapperX<IsAdjustedWorkdayDO>().betweenIfPresent(IsAdjustedWorkdayDO::getAdjustedWorkday, pageReqVO.getStartResourceDate(), pageReqVO.getEndResourceDate()));
        //根据 AreaResourcesDO 初始化一个没有指定日期的 List<AreaBookingQuotaDO> 方便后续处理

        List<AreaResourcesDO> listAreaResources = areaResourcesMapper.selectList();
        //创建一个循环，检查该日是否为工作日
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(pageReqVO.getStartResourceDate());
        Predicate<Calendar> isWeekendFun = cal -> {
            int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
            return dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY;
        };

        while (!calendar.getTime().after(pageReqVO.getEndResourceDate())) {
            Date test = calendar.getTime();
            boolean isWeekend = isWeekendFun.test(calendar);
            boolean isHoliday = listHoliday.stream().anyMatch(day -> day.getHolidayDate().equals(calendar.getTime()) );
            boolean isAdjuested = listAdjustedWorkday.stream().anyMatch(day -> day.getAdjustedWorkday().equals(calendar.getTime()));

            if (!isWeekend && !isHoliday || isAdjuested) {
                List<AreaBookingQuotaDO> preInsert = listAreaResources.stream()
                        .map(single -> {
                            AreaBookingQuotaDO areaBookingQuotaDO = new AreaBookingQuotaDO();
                            areaBookingQuotaDO.setOfficeName(single.getOfficeName());
                            areaBookingQuotaDO.setAreaName(single.getAreaName());
                            areaBookingQuotaDO.setAmSeatCount(single.getSeatCount());
                            areaBookingQuotaDO.setPmSeatCount(single.getSeatCount());
                            areaBookingQuotaDO.setResourceDate(calendar.getTime());
                            return areaBookingQuotaDO;
                        }).collect(Collectors.toList());
                areaBookingQuotaMapper.insertBatch(preInsert);

                List<BookingSeatRecordDO> prebookingSeatRecord = listAreaResources.stream()
                        .map(single -> {
                            BookingSeatRecordDO prebookingSeatRecordDO = new BookingSeatRecordDO();
                            prebookingSeatRecordDO.setOfficeName(single.getOfficeName());
                            prebookingSeatRecordDO.setAreaName(single.getAreaName());
                            prebookingSeatRecordDO.setResourceDate(calendar.getTime());
                            prebookingSeatRecordDO.setAmSeatCount(single.getSeatCount());
                            prebookingSeatRecordDO.setPmSeatCount(single.getSeatCount());
                            prebookingSeatRecordDO.setBookedAmSeat(single.getSeatCountBlocked());
                            prebookingSeatRecordDO.setBookedPmSeat(single.getSeatCountBlocked());
                            prebookingSeatRecordDO.setLeftAmSeat(single.getSeatCount() - single.getSeatCountBlocked());
                            prebookingSeatRecordDO.setLeftPmSeat(single.getSeatCount() - single.getSeatCountBlocked());

                            return prebookingSeatRecordDO;
                        }).collect(Collectors.toList());

                prebookingSeatRecord.stream().forEach(single ->{
                    bookingSeatRecordMapper.delete(new LambdaQueryWrapperX<BookingSeatRecordDO>()
                            .eq(BookingSeatRecordDO::getOfficeName, single.getOfficeName())
                            .eq(BookingSeatRecordDO::getAreaName, single.getAreaName())
                            .eq(BookingSeatRecordDO::getResourceDate,single.getResourceDate()));
                });

                bookingSeatRecordMapper.insertOrUpdateBatch(prebookingSeatRecord);
            }
            calendar.add(Calendar.DATE, 1);
        }
    }

    public BookingUserRecordRespVO BookSeat(BookingUserRecordReqVO pageReqVO) {
        BookingUserRecordRespVO result = new BookingUserRecordRespVO();
        MdmEmployeeDO employeeDO = this.getCurUser();
        String commentResult = "";
        Boolean hasError = false;
        if(pageReqVO!= null && employeeDO != null && employeeDO.getEmployeeCode()!= null)
        {
            result.setEmployeeCode(employeeDO.getEmployeeCode());
            result.setOfficeName(pageReqVO.getOfficeName());
            result.setAreaName(pageReqVO.getAreaName());
            result.setResourceDate(pageReqVO.getResourceDate());
            result.setType(pageReqVO.getType());
            result.setStatus(pageReqVO.getStatus());
        }
        else {
            result.setComment("传入参数为空，操作失败；");
            return result;
        }

        //检查是否允许预订当日多个座位
        if(!pageReqVO.getCanBookMultiSeat()) {

            List<BookingUserRecordDO> usrHistory = bookingUserRecordMapper.selectList(new LambdaQueryWrapperX<BookingUserRecordDO>()
                    .eq(BookingUserRecordDO::getEmployeeCode, employeeDO.getEmployeeCode())
                    .eq(BookingUserRecordDO::getOfficeName, pageReqVO.getOfficeName())
//                    .eq(BookingUserRecordDO::getAreaName, pageReqVO.getAreaName())
                    .eq(BookingUserRecordDO::getResourceDate, pageReqVO.getResourceDate())
                    .eq(BookingUserRecordDO::getStatus, 1));

            if (usrHistory!= null && usrHistory.size()>0){
                if (pageReqVO.getType().equals("am") || pageReqVO.getType().equals("all")){
                    Optional<BookingUserRecordDO> record = usrHistory.stream()
                            .filter(res -> "am".equals(res.getType()))
                            .findFirst();
                    if (record.isPresent()) {
                        hasError = true;
                        commentResult+="您已预约《"+record.get().getAreaName()+"区》上午，请勿重复预约；";
                    }
                }

                if (pageReqVO.getType().equals("pm") || pageReqVO.getType().equals("all")){
                    Optional<BookingUserRecordDO> record = usrHistory.stream()
                            .filter(res -> "pm".equals(res.getType()))
                            .findFirst();
                    if (record.isPresent()) {
                        hasError = true;
                        commentResult+="您已预约《"+record.get().getAreaName()+"区》下午，请勿重复预约；";
                    }
                }
            }
        }

        if(hasError) {
            result.setComment(commentResult);
            return result;
        }

        AreaBookingQuotaPageReqVO query = new AreaBookingQuotaPageReqVO();
        query.setOfficeName(pageReqVO.getOfficeName());
        query.setAreaName(pageReqVO.getAreaName());
        query.setResourceDate(pageReqVO.getResourceDate());
        BookingSeatRecordDO seat = bookingSeatRecordMapper.selectOne(new LambdaQueryWrapperX<BookingSeatRecordDO>()
                        .eq(BookingSeatRecordDO::getOfficeName,pageReqVO.getOfficeName())
                        .eq(BookingSeatRecordDO::getAreaName,pageReqVO.getAreaName())
                        .eq(BookingSeatRecordDO::getResourceDate,pageReqVO.getResourceDate())
        );
        if (seat != null && seat.getId() != null) {
            if((pageReqVO.getType().equals("am") || pageReqVO.getType().equals("all")) && seat.getLeftAmSeat()<1){
                hasError = true;
                commentResult += "上午已订满，请刷新界面，预订失败";
            }

            if((pageReqVO.getType().equals("pm") || pageReqVO.getType().equals("all")) && seat.getLeftPmSeat()<1){
                hasError = true;
                commentResult += "下午已订满，请刷新界面，预订失败";
            }
        }
        else {
            hasError = true;
            commentResult +="未检索到当日的坐席资源，预订失败";
        }


        if(hasError) {
            result.setComment(commentResult);
            return result;
        }

        if((pageReqVO.getType().equals("am") || pageReqVO.getType().equals("all")) && pageReqVO.getStatus().equals(Boolean.TRUE)){
            BookingUserRecordDO newBook = new  BookingUserRecordDO();
            newBook.setOfficeName(pageReqVO.getOfficeName());
            newBook.setAreaName(pageReqVO.getAreaName());
            newBook.setResourceDate(pageReqVO.getResourceDate());
            newBook.setEmployeeCode(employeeDO.getEmployeeCode());
            newBook.setType("am");
            newBook.setStatus(Boolean.TRUE);
            newBook.setComment(pageReqVO.getComment());

            bookingUserRecordMapper.insert(newBook);
        }

        if((pageReqVO.getType().equals("pm") || pageReqVO.getType().equals("all")) && pageReqVO.getStatus().equals(Boolean.TRUE)){
            BookingUserRecordDO newBook = new  BookingUserRecordDO();
            newBook.setOfficeName(pageReqVO.getOfficeName());
            newBook.setAreaName(pageReqVO.getAreaName());
            newBook.setResourceDate(pageReqVO.getResourceDate());
            newBook.setEmployeeCode(employeeDO.getEmployeeCode());
            newBook.setType("pm");
            newBook.setStatus(Boolean.TRUE);
            newBook.setComment(pageReqVO.getComment());

            bookingUserRecordMapper.insert(newBook);
        }
        // 获得用户基本信息
        AdminUserDO user = userService.getUser(getLoginUserId());
        if(user!=null){
            textMsgSendService.TextMsgSend(user.getRemark(),pageReqVO.getAreaName(),pageReqVO.getType(),pageReqVO.getResourceDate(),"shanghai-reserve");
        }
        if((pageReqVO.getType().equals("am") || pageReqVO.getType().equals("all")) && pageReqVO.getStatus().equals(Boolean.TRUE)) {
            seat.setBookedAmSeat(seat.getBookedAmSeat()+1);
            seat.setLeftAmSeat(seat.getLeftAmSeat()-1);
        }
        if((pageReqVO.getType().equals("pm") || pageReqVO.getType().equals("all")) && pageReqVO.getStatus().equals(Boolean.TRUE)) {
            seat.setBookedPmSeat(seat.getBookedPmSeat()+1);
            seat.setLeftPmSeat(seat.getLeftPmSeat()-1);
        }

        bookingSeatRecordMapper.updateById(seat);
        result.setComment("预订成功");


        return result;
    }

    public BookingUserRecordRespVO CancelSeat(BookingUserRecordReqVO pageReqVO) {
        BookingUserRecordRespVO result = new BookingUserRecordRespVO();
        MdmEmployeeDO employeeDO = this.getCurUser();
        String commentResult = "";
        Boolean hasError = false;
        if(pageReqVO!= null && employeeDO != null && employeeDO.getEmployeeCode() != null)
        {
            result.setRecordId(pageReqVO.getRecordId());
            result.setEmployeeCode(employeeDO.getEmployeeCode());
            result.setOfficeName(pageReqVO.getOfficeName());
            result.setAreaName(pageReqVO.getAreaName());
            result.setResourceDate(pageReqVO.getResourceDate());
            result.setType(pageReqVO.getType());
            result.setStatus(pageReqVO.getStatus());
        }
        else {
            result.setComment("传入参数为空，操作失败；");
            return result;
        }


        if(hasError) {
            result.setComment(commentResult);
            return result;
        }

        //检查待取消记录状态
        BookingUserRecordDO cur = bookingUserRecordMapper.selectOne(new LambdaQueryWrapperX<BookingUserRecordDO>()
                .eqIfPresent(BookingUserRecordDO::getId,pageReqVO.getRecordId())
                .eqIfPresent(BookingUserRecordDO::getEmployeeCode,employeeDO.getEmployeeCode()));

        if (cur != null && cur.getId() != null && cur.getStatus() == Boolean.FALSE) {
            result.setComment("已取消，无需重复取消");
            return result;
        } else if (cur == null) {
            result.setComment("未找到对应预约记录，取消预约失败");
            return result;
        }


        //检查当前坐席资源池的情况
        BookingSeatRecordDO seat = bookingSeatRecordMapper.selectOne(new LambdaQueryWrapperX<BookingSeatRecordDO>()
                .eqIfPresent(BookingSeatRecordDO::getOfficeName,cur.getOfficeName())
                .eqIfPresent(BookingSeatRecordDO::getAreaName,cur.getAreaName())
                .eqIfPresent(BookingSeatRecordDO::getResourceDate,cur.getResourceDate()));

        if (seat!= null && seat.getId()!= null){
            if (cur.getType().equals("am") && (seat.getLeftAmSeat() == seat.getAmSeatCount() || seat.getBookedAmSeat() == 0)){
                hasError = true;
                commentResult += "上午资源池溢出，取消预约失败";
            }
            if (cur.getType().equals("pm") && (seat.getLeftPmSeat() == seat.getPmSeatCount() || seat.getBookedPmSeat() == 0)){
                hasError = true;
                commentResult += "上午资源池溢出，取消预约失败";
            }
        }
        else {
            result.setComment("未查到当日坐席资源，取消预约失败");
            return result;
        }

        if(hasError) {
            result.setComment(commentResult);
            return result;
        }


        //取消用户预约记录
        cur.setStatus(Boolean.FALSE);
        bookingUserRecordMapper.updateById(cur);
        AdminUserDO user = userService.getUser(getLoginUserId());
        if(user!=null){
            textMsgSendService.TextMsgSend(user.getRemark(),cur.getAreaName(),cur.getType(),cur.getResourceDate(),"shanghai-cancel");
        }
        //还原当日坐席
        if(cur.getType().equals("am") && cur.getStatus() == Boolean.FALSE) {
            seat.setBookedAmSeat(seat.getBookedAmSeat()-1);
            seat.setLeftAmSeat(seat.getLeftAmSeat()+1);
        }
        if(cur.getType().equals("pm") && cur.getStatus() == Boolean.FALSE) {
            seat.setBookedPmSeat(seat.getBookedPmSeat()-1);
            seat.setLeftPmSeat(seat.getLeftPmSeat()+1);
        }

        bookingSeatRecordMapper.updateById(seat);
        result.setComment("取消预订成功");

        return result;
    }

    public List<BookingUserRecordRespVO> getBookedUserRecord(BookingUserRecordReqVO pageReqVO) {
        List<BookingUserRecordRespVO> listResult = new ArrayList<>();
        MdmEmployeeDO employee = this.getCurUser();
        if (employee!=null && employee.getId() != null) {
            List<BookingUserRecordDO> listDo = bookingUserRecordMapper.selectList(new LambdaQueryWrapperX<BookingUserRecordDO>()
                    .eq(BookingUserRecordDO::getEmployeeCode,employee.getEmployeeCode())
                    .orderByDesc(BookingUserRecordDO::getResourceDate)
                    .orderByAsc(BookingUserRecordDO::getType));
            if(listDo != null && listDo.size() > 0) {
                listDo.forEach(record -> {
                    BookingUserRecordRespVO newOne = new BookingUserRecordRespVO();
                    newOne.setOfficeName(record.getOfficeName());
                    newOne.setAreaName(record.getAreaName());
                    newOne.setEmployeeCode(record.getEmployeeCode());
                    newOne.setResourceDate(record.getResourceDate());
                    newOne.setType(record.getType());
                    newOne.setStatus(record.getStatus());
                    newOne.setRecordId(record.getId());
                    newOne.setComment(record.getComment());
                    listResult.add(newOne);
                });

            }
        }
        return listResult;
    }

    public MdmEmployeeDO getCurUser(){
        AdminUserDO user = userService.getUser(getLoginUserId());
        if(user!=null){
            MdmEmployeeDO employee = mdmEmployeeMapper.selectOne(new LambdaQueryWrapperX<MdmEmployeeDO>()
                    .eq(MdmEmployeeDO::getEmployeeCode,user.getRemark()));
            return employee;
        }
        else{
            return new MdmEmployeeDO();
        }
    }

    public List<BookedSeatRecordRespVO> getSeatListByUser(BookingUserRecordReqVO pageReqVO) {
        List<BookingSeatRecordDO> listBookingSeat = new ArrayList<>();
        MdmEmployeeDO employee = this.getCurUser();
        if (employee!=null && employee.getId() != null) {
            List<AreaDepartementDO> deptList = areaDepartementMapper.selectList(new LambdaQueryWrapperX<AreaDepartementDO>()
                    .eq(AreaDepartementDO::getDepartmentName,employee.getDeptName()));
            if (deptList!=null && deptList.size()>0) {
                deptList.stream().forEach(dept->{
                    List<BookingSeatRecordDO> seat = bookingSeatRecordMapper.selectList(new LambdaQueryWrapperX<BookingSeatRecordDO>()
                            .eq(BookingSeatRecordDO::getOfficeName,dept.getOfficeName())
                            .eq(BookingSeatRecordDO::getAreaName,dept.getAreaName())
                            .ge(BookingSeatRecordDO::getResourceDate,pageReqVO.getResourceDate())
                            .orderByAsc(BookingSeatRecordDO::getResourceDate)
                            .last("LIMIT " + String.valueOf(pageReqVO.getRecentDays()))
                    );
                    if (seat!= null && seat.size()>0) {
                        seat.forEach(one->{
                            listBookingSeat.add(one);
                        });
                    }


                });
            }
        }


        List<BookedSeatRecordRespVO> test = new ArrayList<>();
        if(listBookingSeat!= null && listBookingSeat.size()>0){
            listBookingSeat.stream().forEach(one->{

                BookedSeatRecordRespVO single = new BookedSeatRecordRespVO();
                single.setOfficeName(one.getOfficeName());
                single.setAreaName(one.getAreaName());
                single.setResourceDate(one.getResourceDate());
                single.setAmSeatCount(one.getAmSeatCount());
                single.setPmSeatCount(one.getPmSeatCount());
                single.setBookedAmSeat(one.getBookedAmSeat());
                single.setBookedPmSeat(one.getBookedPmSeat());
                single.setLeftAmSeat(one.getLeftAmSeat());
                single.setLeftPmSeat(one.getLeftPmSeat());
                test.add(single);
            });
        }
        return test;

    }

    public List<BookedSeatRecordRespVO> getSeatListByUserForAdmin(BookingUserRecordReqVO pageReqVO) {
        List<BookingSeatRecordDO> listBookingSeat = new ArrayList<>();
        MdmEmployeeDO employee = this.getCurUser();
        if (employee!=null && employee.getId() != null) {
            List<AreaDepartementDO> deptList = areaDepartementMapper.selectList(new LambdaQueryWrapperX<AreaDepartementDO>());
            if (deptList!=null && deptList.size()>0) {
                deptList.stream().forEach(dept->{
                    List<BookingSeatRecordDO> seat = bookingSeatRecordMapper.selectList(new LambdaQueryWrapperX<BookingSeatRecordDO>()
                            .eq(BookingSeatRecordDO::getOfficeName,dept.getOfficeName())
                            .eq(BookingSeatRecordDO::getAreaName,dept.getAreaName())
                            .ge(BookingSeatRecordDO::getResourceDate,pageReqVO.getResourceDate())
                            .orderByAsc(BookingSeatRecordDO::getResourceDate)
                            .last("LIMIT " + String.valueOf(pageReqVO.getRecentDays()))
                    );
                    if (seat!= null && seat.size()>0) {
                        seat.forEach(one->{
                            if (!listBookingSeat.contains(one)){
                                listBookingSeat.add(one);
                            }

                        });
                    }


                });
            }
        }


        List<BookedSeatRecordRespVO> test = new ArrayList<>();
        if(listBookingSeat!= null && listBookingSeat.size()>0){
            listBookingSeat.stream().forEach(one->{

                BookedSeatRecordRespVO single = new BookedSeatRecordRespVO();
                single.setOfficeName(one.getOfficeName());
                single.setAreaName(one.getAreaName());
                single.setResourceDate(one.getResourceDate());
                single.setAmSeatCount(one.getAmSeatCount());
                single.setPmSeatCount(one.getPmSeatCount());
                single.setBookedAmSeat(one.getBookedAmSeat());
                single.setBookedPmSeat(one.getBookedPmSeat());
                single.setLeftAmSeat(one.getLeftAmSeat());
                single.setLeftPmSeat(one.getLeftPmSeat());
                test.add(single);
            });
        }
        return test;

    }


}


